package com.leetcode.hot100;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode.hot100
 * @Author: lei
 * @CreateTime: 2024-03-21  13:25
 * @Description: TODO
 * @Version: 1.0
 */
public class 两数之和_01 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        System.out.println(Arrays.toString(twoSum(nums, target)));
    }

    public static int[] twoSum(int[] nums, int target) {
        // key 为数组上的元素取值 value 为数组中元素的索引位置信息
        Map<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int key = target - nums[i];
            if (hashMap.containsKey(key)) {
                return new int[]{i, hashMap.get(key)};
            }
            hashMap.put(nums[i], i);
        }
        return new int[]{};
    }
}
